package com.zhan.drugStore.controller;

import com.zhan.drugStore.enums.ResultEnum;
import com.zhan.drugStore.service.*;
import com.zhan.drugStore.util.ResponseBase;
import com.zhan.drugStore.util.ResponseBean;
import com.zhan.drugStore.util.SourceBean;
import com.zhan.drugStore.util.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;


@Controller
@Slf4j
@SuppressWarnings("all")
public class SuperController {

    private static final Logger logger = LoggerFactory.getLogger(SuperController.class);
    protected static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;
    @Autowired
    protected BillService billService;
    @Autowired
    protected CustomerService customerService;
    @Autowired
    protected UserService userService;
    @Autowired
    protected HobbyService hobbyService;

    /**
     * 返回result对象
     *
     * @return
     */
    protected ResponseBase resultSuccess() {
        return new ResponseBase().success();
    }

    /**
     * 返回result对象
     *
     * @param <T>
     * @return 响应对象
     */
    protected <T> ResponseBean<T> resultSuccess(T t) {
        return new ResponseBean<T>().success(t);
    }

    /**
     * 返回result对象
     *
     * @return 响应对象
     */
    protected ResponseBase resultBase(ResultEnum resultEnum) {
        ResponseBase result = new ResponseBase();
        result.setCode(resultEnum.getCode());
        result.setMessage(resultEnum.getMessage());
        return result;
    }

    /**
     * 返回result异常对象
     *
     * @return
     */
    protected ResponseBase resultCatch() {
        return this.resultBase(ResultEnum.ERROR);
    }

    /**
     * 返回result对象
     *
     * @return 响应对象
     */
    protected ResponseBase resultBase(String errMsg) {
        ResponseBase result = new ResponseBase();
        result.setCode(ResultEnum.ERROR.getCode());
        result.setMessage(errMsg);
        return result;
    }

    /**
     * 获取SourceBean
     *
     * @return SourceBean
     */
    protected SourceBean getSource() {
        String sessionId = request.getParameter("access_token");
        String geoX = request.getParameter("geoX");
        String geoY = request.getParameter("geoY");
        String deviceID = request.getParameter("deviceID");

        SourceBean sourceBean = new SourceBean();
        if (!ToolUtils.isTrimEmpty(sessionId))
            sourceBean.setSessionId(sessionId);
        if (!ToolUtils.isTrimEmpty(deviceID))
            sourceBean.setDeviceID(deviceID);
        if (!ToolUtils.isTrimEmpty(geoX))
            sourceBean.setGeoX(ToolUtils.genDouble(geoX));
        if (!ToolUtils.isTrimEmpty(geoY))
            sourceBean.setGeoY(ToolUtils.genDouble(geoY));

        sourceBean.setSource(SourceBean.sources_admin);
        sourceBean.setIp(this.getIpAddr());
        return sourceBean;
    }

    /**
     * 获取真实ip地址
     */
    private String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    logger.error("获取本机配置IP出错：", e);
                }
                ip = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

}
